package com.yhsoft.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.sys.entity.Menu;
import com.yhsoft.sys.entity.User;
import com.yhsoft.sys.mapper.MenuMapper;
import com.yhsoft.sys.service.IMenuService;
import com.yhsoft.sys.service.IRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-08-30
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private IRoleService roleService;

    @Override
    public List<Menu> getAllMenu() {
        User user = roleService.getUserInfoByToken();
        // 一级菜单
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Menu::getParentId,0);
        wrapper.eq(Menu::getSysType,user.getSysType());
        List<Menu> menuList = this.list(wrapper);
        // 填充子菜单
        setMenuChildren(menuList,user.getSysType());
        log.debug("--------" + menuList.toString());
        return menuList;
    }


    private void setMenuChildren(List<Menu> menuList,String sysType) {
        if(menuList != null){
            for (Menu menu : menuList) {
                LambdaQueryWrapper<Menu> subWrapper = new LambdaQueryWrapper<>();
                subWrapper.eq(Menu::getParentId,menu.getMenuId());
                subWrapper.eq(Menu::getSysType,sysType);
                List<Menu> subMenuList = this.list(subWrapper);
                menu.setChildren(subMenuList);
                // 递归
                setMenuChildren(subMenuList,sysType);
            }
        }
    }

    @Override
    public List<Menu> getMenuListByUserId(User user) {
        String userId = user.getId();
        // 管理员账号直接获取该类型的所有菜单
        if(user.getIsAdmin() != null  && user.getIsAdmin().equals(1)){
            userId = null;
        }
        // 一级菜单
        List<Menu> menuList = this.baseMapper.getMunuListByUserId(userId, 0,user.getSysType());
        // 子菜单
        setMenuChildrenByUserId(userId, menuList,user);
        log.debug("--------1" + menuList.toString());
        return menuList;
    }

    private void setMenuChildrenByUserId(String userId, List<Menu> menuList,User user) {
        if(menuList != null){
            for (Menu menu : menuList) {
                List<Menu> subMenuList = this.baseMapper.getMunuListByUserId(userId, menu.getMenuId(),user.getSysType());
                menu.setChildren(subMenuList);
                // 递归
                setMenuChildrenByUserId(userId,subMenuList,user);
            }
        }
    }

}
